package net.ib.mtalk.ui.setting.restore;

import net.ib.mntalk.protocol.Common;
import net.ib.mntalk.protocol.Common.BuddyInfo;
import net.ib.mntalk.protocol.Common.SuggestionReasonKnowsOption;
import net.ib.mntalk.protocol.Common.SuggestionTarget;
import net.ib.mntalk.protocol.Session.SetBuddyInfoReq;
import net.ib.mntalk.protocol.Session.SetSuggestionsReq;
import net.ib.mtalk.R;
import net.ib.mtalk.base.BaseActivity;
import net.ib.mtalk.constant.HandlerMsgConst;
import net.ib.mtalk.database.DatabaseContract.BuddyTable;
import net.ib.mtalk.database.DatabaseContract.SuggestionTable;
import net.ib.mtalk.database.helper.BuddyDatabaseHelper;
import net.ib.mtalk.database.helper.SuggestionDatabaseHelper;
import net.ib.mtalk.network.task.SetBuddyinfoTask;
import net.ib.mtalk.network.task.SetSuggestionTask;
import net.ib.mtalk.util.GpbSupport;
import net.ib.mtalk.util.ProfileImageLoader;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.protobuf.micro.InvalidProtocolBufferMicroException;

public class RestoreActivity extends BaseActivity
{
	public final static int MODE_DELETE_FRIEND = 0;
	public final static int MODE_DELETE_SUGGESTION = 1;
	public final static int MODE_BLOCK_FRIEND = 2;
	
	public final static String KEY_MODE = "mode";
	
	private ListView mListView;
	private int mMode;
	private Context mContext;
	private CursorAdapter mAdapter;
	//private SetBuddyInfoReq mSetBuddyInfoReq;
	
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			switch(msg.what){
			case HandlerMsgConst.HANDLER_UNKNOWN_ERROR:
				Toast.makeText(mContext, "HANDLER_UNKNOWN_ERROR", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_SET_BUDDY_INFO_SUCCESS:
				//BuddyDatabaseHelper.updateBuddyStatus(mContext, mSetBuddyInfoReq);
				Toast.makeText(mContext, "HANDLER_SET_BUDDY_INFO_SUCCESS", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_SET_BUDDY_INFO_FAIL:
				Toast.makeText(mContext, "HANDLER_SET_BUDDY_INFO_FAIL", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_SET_SUGGESTION_SUCCESS:
				String name = (String) msg.obj;
				Toast.makeText(mContext, name + " is restored.", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_SET_SUGGESTION_FAIL:
				Toast.makeText(mContext, "HANDLER_SET_SUGGESTION_FAIL", Toast.LENGTH_SHORT).show();
				break;
			default:
				break;
			}
		};
	};
	
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_restore);
		mContext = this;
		
		mMode = getIntent().getIntExtra(KEY_MODE, -1);
		mListView = (ListView)findViewById(R.id.listview);
		
		initAdapter();
		mListView.setAdapter(mAdapter);
	}

	public void onDestroy()
	{
		super.onDestroy();
		if(mAdapter != null)
			mAdapter.getCursor().close();
	}
	
	public void initAdapter()
	{
		Cursor cursor = null;
		switch(mMode)
		{
		case MODE_DELETE_FRIEND:
			cursor = BuddyDatabaseHelper.selectRemoveBuddy(mContext);
			break;
		case MODE_BLOCK_FRIEND:
			cursor = BuddyDatabaseHelper.selectBlockBuddy(mContext);
			break;
		case MODE_DELETE_SUGGESTION:
			cursor = SuggestionDatabaseHelper.selectDeleteSuggestion(mContext);
			break;
		default:
			break;
		}
		
		cursor.moveToFirst();
		mAdapter = new RestoreAdapter(mContext, cursor);
	}
	
	private class RestoreAdapter extends CursorAdapter
	{
		public RestoreAdapter(Context context, Cursor c) 
		{
			super(context, c, true);
		}
		
		private class TagItem 
		{
			public ImageView tvImage;
			public TextView tvName;
			public TextView tvStatus;
			public Button btnRestore;
		}
		
		private TagItem getTagItem(View view) 
		{
			TagItem tagItem = new TagItem();
			
			tagItem.tvImage = (ImageView) view.findViewById(R.id.restore_item_image);
			tagItem.tvName = (TextView) view.findViewById(R.id.restore_item_name);
			tagItem.tvStatus = (TextView) view.findViewById(R.id.restore_item_status);
			tagItem.btnRestore = (Button) view.findViewById(R.id.restore_item_btn);
			return tagItem;
		}
		

		public void bindView(View view, Context context, final Cursor cursor) 
		{
			final int position = cursor.getPosition();
			TagItem tag = (TagItem) view.getTag();
			
			if(mMode == MODE_DELETE_SUGGESTION)
			{
				tag.tvName.setText(cursor.getString(cursor.getColumnIndexOrThrow(SuggestionTable.KEY_DISPLAYNAME)));
				
				ProfileImageLoader.getInstance(mContext).loadProfileImage(tag.tvImage, 
						GpbSupport.UuidMsgToString(GpbSupport.makeUuidMsg(cursor.getLong(cursor.getColumnIndexOrThrow(SuggestionTable.KEY_SUGGESTION_UUID_MSB)), 
																		  cursor.getLong(cursor.getColumnIndexOrThrow(SuggestionTable.KEY_SUGGESTION_UUID_LSB)))));
			} 
			else 
			{
				tag.tvName.setText(cursor.getString(cursor.getColumnIndexOrThrow(BuddyTable.KEY_BUDDY_DISPLAYNICK)));
				
				ProfileImageLoader.getInstance(mContext).loadProfileImage(tag.tvImage, 
						GpbSupport.UuidMsgToString(GpbSupport.makeUuidMsg(cursor.getLong(cursor.getColumnIndexOrThrow(BuddyTable.KEY_BUDDY_UUID_MSB)), 
																		  cursor.getLong(cursor.getColumnIndexOrThrow(BuddyTable.KEY_BUDDY_UUID_LSB)))));
				
				try {
					BuddyInfo buddyInfo = BuddyInfo.parseFrom(cursor.getBlob(cursor.getColumnIndexOrThrow(BuddyTable.KEY_BUDDY_INFO)));
					String statusMsg = buddyInfo.getProfile().getStatus();
					if(statusMsg != null && statusMsg.trim().length() > 0)
					{
						tag.tvStatus.setVisibility(View.VISIBLE);
						tag.tvStatus.setText(statusMsg);
					}
					else
						tag.tvStatus.setVisibility(View.INVISIBLE);
				} catch (InvalidProtocolBufferMicroException e) {
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				}
			}
			
			if(mMode == MODE_BLOCK_FRIEND)
				tag.btnRestore.setText(getString(R.string.unblock));
			else if(mMode == MODE_DELETE_FRIEND)
				tag.btnRestore.setText(getString(R.string.restore));
			else
				tag.btnRestore.setText(getString(R.string.restore));
			
			tag.btnRestore.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) 
				{
					cursor.moveToPosition(position);
					
					if(mMode == MODE_DELETE_SUGGESTION)
					{
						try {
							long msb = cursor.getLong(cursor.getColumnIndexOrThrow(SuggestionTable.KEY_SUGGESTION_UUID_MSB));
							long lsb = cursor.getLong(cursor.getColumnIndexOrThrow(SuggestionTable.KEY_SUGGESTION_UUID_LSB));
							SetSuggestionsReq setSuggestionsReq = new SetSuggestionsReq();
							setSuggestionsReq.addTarget(new Common.SuggestionTarget().setType(Common.USER_OBJ)
									 .setObjectUuid(GpbSupport.makeUuidMsg(msb, lsb)));
							setSuggestionsReq.setStatusType(Common.SUGGESTION_STATUS_NORMAL);
							
							SuggestionReasonKnowsOption option = SuggestionReasonKnowsOption.parseFrom(mAdapter.getCursor().getBlob(mAdapter.getCursor().getColumnIndexOrThrow(SuggestionTable.KEY_KNOWS_OPTIONS)));
							String name = option.getKnowsProfile().getName().getDisplayName();
							SetSuggestionTask task = new SetSuggestionTask(mContext, mHandler, setSuggestionsReq, name);
							task.execute();
						} catch (InvalidProtocolBufferMicroException e) {
							e.printStackTrace();
						} catch (IllegalArgumentException e) {
							e.printStackTrace();
						}
					}
					else
					{
						try {
							BuddyInfo buddyInfo = BuddyInfo.parseFrom(cursor.getBlob(cursor.getColumnIndexOrThrow(BuddyTable.KEY_BUDDY_INFO)));
							buddyInfo.setBuddyStatus(Common.BUDDY_STATUS_NORMAL);
							SetBuddyInfoReq setBuddyInfoReq = new SetBuddyInfoReq();
							setBuddyInfoReq.setBuddyInfo(buddyInfo);
							setBuddyInfoReq.addProperty(Common.BUDDY_STATUS);
							
							SetBuddyinfoTask setBuddyinfoTask = new SetBuddyinfoTask(mContext, mHandler, setBuddyInfoReq);
							setBuddyinfoTask.execute();
						} catch (InvalidProtocolBufferMicroException e) {
							e.printStackTrace();
						} catch (IllegalArgumentException e) {
							e.printStackTrace();
						}
					}
				}
			});
		}

		public View newView(Context context, final Cursor cursor, ViewGroup parent) 
		{
			LayoutInflater inflater = LayoutInflater.from(context);
			View newView = inflater.inflate(R.layout.list_item_restore, parent, false);
			
			TagItem tag = getTagItem(newView);
			newView.setTag(tag);
			

			return newView;
		}
	}
}
